import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/views/layout/index'
import Dashboard from '@/views/dashboard/Dashboard'
import List from '@/views/basic/List'
import Card from '@/views/basic/Card'
import UserList from '@/views/admin/user/UserList'
import UserCard from '@/views/admin/user/UserCard'
import TaskList from '@/views/admin/task/TaskList'
import TaskCard from '@/views/admin/task/TaskCard'
import Error404 from '@/views/errors/404'
import Error403 from '@/views/errors/403'
import Error500 from '@/views/errors/500'
import Login from '@/views/login/Login'
import store from '@/store'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
    },
    {
      path: '/',
      name: 'layout',
      component: Layout,
      children: [
        { path: 'dashboard', name: 'dashboard', component: Dashboard },
        { path: 'list', name: 'list', component: List },
        { path: 'card', name: 'card', component: Card },
        { path: 'userList', name: 'userList', component: UserList },
        { path: 'userCard', name: 'userCard', component: UserCard },
        { path: 'taskList', name: 'taskList', component: TaskList },
        { path: 'taskCard', name: 'taskCard', component: TaskCard },
        { path: 'error404', name: 'error404', component: Error404 },
        { path: 'error403', name: 'error403', component: Error403 },
        { path: 'error500', name: 'error500', component: Error500 }
      ]
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  // 1. 判断是否有token
  const hasToken = store.getters['user/token'];
  if (!hasToken) {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
    return
  }

  // 2. 已经登录，跳转到登录页则重定向到首页
  if (to.path === '/login') {
    next('/')
    return
  }
  
  // 确保用户信息已加载
  try {
    if (!store.getters['user/userInfo']) {
      await store.dispatch('user/getUserInfo',hasToken);
    }
    next();
  } catch (error) {
    await store.dispatch('user/logout');
    next('/login');
    return;
  }
  
})

export default router